package com.store.app.fragment;

import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.store.app.R;
import com.store.app.adapter.OrderFreeAdapter;
import com.store.app.bean.EventBusBean;
import com.store.app.bean.FreeBean;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.utils.ToastUtils;
import com.store.app.utils.Utils;
import com.store.app.widget.AutoListView;
import com.store.app.widget.AutoListView.OnLoadListener;
import com.store.app.widget.AutoListView.OnRefreshListener;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;


//领了么订单Fragment
public class TheOrderFreeFragment extends Fragment implements IOnHttpListener,View.OnClickListener{
	private View v;
	private AutoListView lv;
	private List<FreeBean> list;
	private OrderFreeAdapter mAdapter;
	//无网络页面
	private LinearLayout lin_loadfail;
	private ImageView img_fail_nonet;
	private ImageView img_fail_notext;
	private TextView tv_fail;
	private  final int MSG_LOAD_SUCCESS = 0;
	private  final int MSG_LOAD_FAILED = 1;

	private  final int MSG_REFRESH_SUCCESS = 2;
	private  final int MSG_REFRESH_FAILED = 3;


	private  final int MSG_DELETE_SUCCESS = 6;
	private  final int MSG_DELETE_FAILED = 7;
	private  final int MSG_LOAD_NOTNET = 8;

	private  final int SEND_SUCC = 10;
	private  final int SEND_FAIL = 11;
	private  final int DOWN_TIME = 12;
	private int pageNum;
	private int pageSize;
	private NetRequest netRequest;
	private String currentStatus = "processing";

	private  long  min_second=0;
	private String showFragmentIndex="0";
	private TextView tv_exception_order;
	private LinearLayout ll_exception_order;
	private String count_num;

	private Runnable runnable = new Runnable( ) {

		public void run ( ) {

			mHandler.sendEmptyMessage(DOWN_TIME);

			mHandler.postDelayed(this, 1000);     //postDelayed(this,1000)方法安排一个Runnable对象到主线程队列中

		}

	};
	private TextView tv1, tv2, tv3, tv4, tv5;

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
				case DOWN_TIME:
					min_second+=1;
					mAdapter.updateProgressPartly(min_second);
					break;

				case MSG_LOAD_SUCCESS:
					Log.v("zyl","onLoadComplete");
					lv.onLoadComplete();
					if (msg.arg1 == pageNum) {
						@SuppressWarnings("unchecked")
						List<FreeBean> result = (List<FreeBean>) msg.obj;
						lv.setResultSize(result.size());
						list.addAll(result);
						mAdapter.notifyDataSetChanged();
						pageNum += 1;

						//开启倒计时
						mHandler.removeCallbacks(runnable);
						mHandler.postDelayed(runnable,1000);
//						if (list.size() == 0) {
//							lin_loadfail.setVisibility(View.VISIBLE);
//							img_fail_nonet.setVisibility(View.GONE);
//							img_fail_notext.setVisibility(View.VISIBLE);
//							tv_fail.setText("暂无内容");
//						}
					}
					break;
				case MSG_LOAD_FAILED:
					lv.setResultSize(0);
					lv.onLoadComplete();
					Toast.makeText(getActivity(),(String) msg.obj,Toast.LENGTH_SHORT).show();
					break;
				case MSG_REFRESH_SUCCESS:
					lv.onRefreshComplete();
					@SuppressWarnings("unchecked")
					List<FreeBean> result = (List<FreeBean>) msg.obj;
					lv.setResultSize(result.size());
					list.clear();
					list.addAll(result);
					mAdapter.notifyDataSetChanged();
					pageNum += 1;
					min_second=0;
					//开启倒计时
					mHandler.removeCallbacks(runnable);
					mHandler.postDelayed(runnable,1000);
					break;
				case MSG_REFRESH_FAILED:
					lv.onRefreshComplete();
					Toast.makeText(getActivity(),(String) msg.obj,Toast.LENGTH_SHORT).show();
					break;
				case MSG_DELETE_SUCCESS:
					lv.onRefresh();
					break;
				case MSG_DELETE_FAILED:
					Toast.makeText(getActivity(),(String) msg.obj,Toast.LENGTH_SHORT).show();
					break;
				case SEND_FAIL:
					Toast.makeText(getActivity(),"确认收货失败!",Toast.LENGTH_SHORT).show();
					break;
				case SEND_SUCC:
					int position = (int) msg.obj;
					list.get(position).setStatus("received");
					mAdapter.notifyDataSetChanged();
					Toast.makeText(getActivity(),"确认收货成功!",Toast.LENGTH_SHORT).show();
					break;
				//无网络
				case MSG_LOAD_NOTNET:
//					lin_loadfail.setVisibility(View.VISIBLE);
//					lin_loadfail.setOnClickListener(new OnClickListener() {
//						@Override
//						public void onClick(View v) {
//					lin_loadfail.setVisibility(View.GONE);
//						lv.onLoad();
//						}
//					});
				default:
					break;
			}
		}
	};


	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		v = inflater.inflate(R.layout.fragment_llm_order, container, false);
		list = new ArrayList<>();
		pageNum = 1;
		pageSize =15;
		findViews();
		setListeners();
		lv.onLoad();
		EventBus.getDefault().register(this);
//		netRequest.requestOrderExceptionCount(4);
		Log.v("zyl","TheOrderFreeFragment");
		return v;
	}
	private void onEvent(EventBusBean busBean){
		if(busBean.type==201){
			pageNum = 1;
			showFragmentIndex = "0";
			currentStatus = "processing";
			netRequest.requestFreeOrderQuery(2, pageNum + "", pageSize + "",currentStatus);
		}
		//跳转到待返款页面
		else if(busBean.type == 227){
			pageNum=1;
			showFragmentIndex = "1";
			refreshUITab(showFragmentIndex);
			currentStatus = "confirmed";
			netRequest.requestFreeOrderQuery(2, pageNum + "", pageSize + "", currentStatus);
		}
		//跳转到已取消
		else if(busBean.type == 228){
			pageNum=1;
			showFragmentIndex = "3";
			refreshUITab(showFragmentIndex);
			currentStatus = "cancelled";
			netRequest.requestFreeOrderQuery(2, pageNum + "", pageSize + "", currentStatus);
		}
	}
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		EventBus.getDefault().unregister(this);
		mHandler.removeCallbacks(runnable);
	}
	private void findViews(){
		netRequest = new NetRequest(this,getActivity());
//		lin_loadfail = (LinearLayout) v.findViewById(R.id.loadfail);
		img_fail_nonet= (ImageView) v.findViewById(R.id.loadfail_nonet);
		img_fail_notext= (ImageView) v.findViewById(R.id.loadfail_notext);
		tv_fail= (TextView) v.findViewById(R.id.loadfail_tv);
		lv = (AutoListView) v.findViewById(R.id.lv_goods);
		lv.setDivider(null);
		mAdapter = new OrderFreeAdapter(list, getActivity(),lv);
		lv.setAdapter(mAdapter);
//		tv_exception_order = (TextView) v.findViewById(R.id.tv_exception_order);
//		ll_exception_order = (LinearLayout) v.findViewById(R.id.ll_exception_order);

		tv1 = (TextView) v.findViewById(R.id.tv_task1);
		tv2 = (TextView) v.findViewById(R.id.tv_task2);
		tv3 = (TextView) v.findViewById(R.id.tv_task3);
		tv4 = (TextView) v.findViewById(R.id.tv_task4);
		tv5 = (TextView) v.findViewById(R.id.tv_task5);
		tv1.setOnClickListener(this);
		tv2.setOnClickListener(this);
		tv3.setOnClickListener(this);
		tv4.setOnClickListener(this);
		tv5.setOnClickListener(this);

	}

	private void setListeners() {


		lv.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				//requestStoreGoodsListRefresh();
//				new requestStoreGoodsListRefresh2().start();
				pageNum = 1;
				netRequest.requestFreeOrderQuery(2, pageNum + "", pageSize + "", currentStatus);
			}
		});

		lv.setOnLoadListener(new OnLoadListener() {

			@Override
			public void onLoad() {
//				new requestStoreGoodsList2().start();
				netRequest.requestFreeOrderQuery(1, pageNum + "", pageSize + "",currentStatus);

			}
		});


	}

	@Override
	public void onAfinalFail() {
		if(getActivity()!=null){
			ToastUtils.showTextToast(getActivity(), "请检查本地网络！");
		}

		if(lv!=null){
			lv.onRefreshComplete();
		}
	}

	@Override
	public void onExecuteSuccess(int requestId, String result, String msg) {
		Log.v("zyl", "fragment result:" + result);
		if(requestId == 1){
			try {
				JSONObject data = new JSONObject(result);
				Log.v("zyl", "data1:" + data.toString());
				Gson gson = new Gson();

				String doc_urls= data.getString("doc_url");
				Map<String,String> map = Utils.getMapForJson(doc_urls);
				JSONArray listArr = data.getJSONArray("list");
				List<FreeBean> OrderBeanList = new ArrayList<>();
				for (int i=0;i<listArr.length();i++){
					FreeBean orderBean = gson.fromJson(listArr.getJSONObject(i).toString(),FreeBean.class);

					try {
						JSONArray jsonArray = new JSONArray(orderBean.getItem_goods_pic_info());
						JSONObject jsonObject = jsonArray.getJSONObject(0);
						String s_id = jsonObject.getString("path_id");
						String url = map.get(s_id);
						if(url==null){
							url="";
						}
						orderBean.setGoods_pic_info_url(url);
					} catch (Exception e) {
						e.printStackTrace();
					}

					OrderBeanList.add(orderBean);
				}
				Message message = Message.obtain();
				message.what = MSG_LOAD_SUCCESS;
				message.arg1 = data.getJSONObject("page").getInt("page_no");

				Log.v("zyl","订单数据："+data.getString("list"));
				message.obj = OrderBeanList;
				mHandler.sendMessage(message);
			}catch (Exception e){
				e.printStackTrace();
			}
		}else if(requestId ==2){
			try {
				JSONObject data = new JSONObject(result);
				Log.v("zyl", "data2:" + data.toString());
				Gson gson = new Gson();

				String doc_urls= data.getString("doc_url");
				Map<String,String> map = Utils.getMapForJson(doc_urls);
				JSONArray listArr = data.getJSONArray("list");
				List<FreeBean> OrderBeanList = new ArrayList<>();
				for (int i=0;i<listArr.length();i++){
					FreeBean orderBean = gson.fromJson(listArr.getJSONObject(i).toString(),FreeBean.class);

					try {
						JSONArray jsonArray = new JSONArray(orderBean.getItem_goods_pic_info());
						JSONObject jsonObject = jsonArray.getJSONObject(0);
						String s_id = jsonObject.getString("path_id");
						String url = map.get(s_id);
						if(url==null){
							url="";
						}
						orderBean.setGoods_pic_info_url(url);
					} catch (Exception e) {
						e.printStackTrace();
					}

					OrderBeanList.add(orderBean);
				}
				Message message = Message.obtain();
				message.what = MSG_REFRESH_SUCCESS;
				message.arg1 = data.getJSONObject("page").getInt("page_no");

				Log.v("zyl", "订单数据：" + data.getString("list"));
				message.obj = OrderBeanList;
				mHandler.sendMessage(message);
			}catch (Exception e){}
		}else if(requestId  ==3){
			Log.v("zyl","收到3:"+result);
		}
		if(requestId == 4){
//			try {
//				JSONObject jsonObject = new JSONObject(result);
//				count_num = jsonObject.getString("count_num");
//				tv_exception_order.setText(count_num);
//				if(count_num!=null&&!count_num.equals("0")){
//					ll_exception_order.setVisibility(View.VISIBLE);
//				}else{
//					ll_exception_order.setVisibility(View.GONE);
//				}
//			}catch (Exception e){
//				e.printStackTrace();
//			}
		}
	}

	@Override
	public void onExecuteFail(int requestId, String msg) {
			Log.v("zyl","失败msg:"+msg);
			if(msg.contains("token")){

			}else{
				if(getActivity()!=null){
					Toast.makeText(getActivity(),msg,Toast.LENGTH_SHORT).show();
				}

			}
	}


	@Override
	public void onClick(View view) {
		switch (view.getId()) {
			//待确认
			case R.id.tv_task1:
				Log.v("zyl","tv_task1");
				pageNum=1;
				showFragmentIndex = "0";
				refreshUITab(showFragmentIndex);
				currentStatus = "processing";
				netRequest.requestFreeOrderQuery(2, pageNum + "", pageSize + "",currentStatus);
				break;
			//待返款
			case R.id.tv_task2:
				Log.v("zyl","tv_task2");
				pageNum=1;
				showFragmentIndex = "1";
				refreshUITab(showFragmentIndex);
				currentStatus = "confirmed";
				netRequest.requestFreeOrderQuery(2, pageNum + "", pageSize + "", currentStatus);
				break;
			//已返款
			case R.id.tv_task3:
				pageNum=1;
				showFragmentIndex = "2";
				refreshUITab(showFragmentIndex);
				currentStatus = "closed";
				netRequest.requestFreeOrderQuery(2, pageNum + "", pageSize + "", currentStatus);
				break;
			//已取消
			case R.id.tv_task4:
				pageNum=1;
				showFragmentIndex = "3";
				refreshUITab(showFragmentIndex);
				currentStatus = "cancelled";
				netRequest.requestFreeOrderQuery(2, pageNum + "", pageSize + "", currentStatus);
				break;
			//全部
			case R.id.tv_task5:
				pageNum=1;
				showFragmentIndex = "4";
				refreshUITab(showFragmentIndex);
				currentStatus = "";
				netRequest.requestFreeOrderQuery(2, pageNum + "", pageSize + "", currentStatus);
				break;
		}
	}

	private void refreshUITab(String index) {
		if (index.equals("0")) {
			tv1.setTextColor(Color.parseColor("#ff403b"));
			tv1.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
			tv2.setTextColor(Color.parseColor("#666666"));
			tv2.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
			tv3.setTextColor(Color.parseColor("#666666"));
			tv3.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
			tv4.setTextColor(Color.parseColor("#666666"));
			tv4.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
			tv5.setTextColor(Color.parseColor("#666666"));
			tv5.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
		} else if (index.equals("1")) {

			tv1.setTextColor(Color.parseColor("#666666"));
			tv1.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
			tv2.setTextColor(Color.parseColor("#ff403b"));
			tv2.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
			tv3.setTextColor(Color.parseColor("#666666"));
			tv3.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
			tv4.setTextColor(Color.parseColor("#666666"));
			tv4.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
			tv5.setTextColor(Color.parseColor("#666666"));
			tv5.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
		} else if (index.equals("2")) {
			tv1.setTextColor(Color.parseColor("#666666"));
			tv1.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
			tv2.setTextColor(Color.parseColor("#666666"));
			tv2.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
			tv3.setTextColor(Color.parseColor("#ff403b"));
			tv3.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
			tv4.setTextColor(Color.parseColor("#666666"));
			tv4.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
			tv5.setTextColor(Color.parseColor("#666666"));
			tv5.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
		} else if (index.equals("3")) {
			tv1.setTextColor(Color.parseColor("#666666"));
			tv1.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
			tv2.setTextColor(Color.parseColor("#666666"));
			tv2.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
			tv3.setTextColor(Color.parseColor("#666666"));
			tv3.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
			tv4.setTextColor(Color.parseColor("#ff403b"));
			tv4.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
			tv5.setTextColor(Color.parseColor("#666666"));
			tv5.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
		} else if (index.equals("4")) {
			tv1.setTextColor(Color.parseColor("#666666"));
			tv1.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
			tv2.setTextColor(Color.parseColor("#666666"));
			tv2.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
			tv3.setTextColor(Color.parseColor("#666666"));
			tv3.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
			tv4.setTextColor(Color.parseColor("#666666"));
			tv4.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
			tv5.setTextColor(Color.parseColor("#ff403b"));
			tv5.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
		}
	}
}